const fs = require('fs');
const os = require('os');
const path = require('path');
const iconv = require('iconv-lite');
const exec = require('child_process').exec;

// 获取当前健康码图片
async function fetch(name, daka_day) {
    const dst = path.join(__dirname, `../img/history/${daka_day || today()}_${name}.jpg`);
    if (!fs.existsSync(dst)) {
        const src = radomFile(name);
        return await paint(src, dst);
    }
    return dst;
}

// 从目录中随机选取一张作为源文件
function radomFile(name) {
    const dir = path.join(__dirname, '../img/', name);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
        return 'dir_empty';
    }
    const arr = fs.readdirSync(dir);
    arr.sort(function () {
        return Math.random() - 0.5
    });
    const tmp = arr[Math.floor((Math.random() * arr.length))];
    return path.join(dir, tmp);
}

// 用JAVA画到目标文件
async function paint(src, dst, time, datetime) {
    const command = `cd "${__dirname}" && javac -encoding utf-8 Main.java && java Main "${src}" "${dst}" "${time || ''}" "${datetime || ''}"`;
    console.log(command);
    return new Promise((resolve, reject) => {
        if (os.platform() === 'win32') {
            exec(command, {encoding: 'gbk'}, function (err, stdout, stderr) {
                if (err) {
                    console.log(iconv.decode(stderr, 'gbk').trim());
                    resolve(null);
                } else {
                    console.log(iconv.decode(stdout, 'gbk').trim());
                    resolve(dst);
                }
            });
        } else {
            exec(command, {encoding: 'utf8'}, function (err, stdout, stderr) {
                if (err) {
                    console.log(stderr.toString().trim());
                    resolve(null);
                } else {
                    console.log(stdout.toString().trim());
                    resolve(dst);
                }
            });
        }
    });
}

// 今天的日期 2021-01-01
function today() {
    const d = new Date();
    return [d.getFullYear(), ('0' + (d.getMonth() + 1)).slice(-2), ('0' + d.getDate()).slice(-2)].join('-');
}

module.exports.fetch = fetch;
module.exports.paint = paint;